/*
 * Copyright (C) 2012-2013  Romain DUBOIS
 * 
 * This file is part of NeMoS - Network and Modular Software
 * 
 * NeMoS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NeMoS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NeMoS.  If not, see <http://www.gnu.org/licenses/>.
 */
package nemos.remote.rsa.message.impl;

import static nemos.remote.rsa.message.MessageConfigurationConstants.CONFIG_NAME;
import static nemos.remote.rsa.message.MessageConfigurationConstants.TRANSPORT_ID_PROPERTY;

import java.util.Collections;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import nemos.remote.rsa.RemoteServiceAdminImpl;
import nemos.remote.rsa.message.MessageConfigurationConstants;
import nemos.remote.rsa.message.transport.ITransport;
import nemos.remote.util.RemoteUtil;

import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
import org.osgi.service.remoteserviceadmin.RemoteConstants;
import org.osgi.service.remoteserviceadmin.RemoteServiceAdmin;

/**
 * TransportRsa : The transport-based Remote Service Admin.
 * 
 * <p>
 * This class relies on the {@link ITransport} for the message transport and
 * uses a provided proxy factory for remote calls.
 * </p>
 * 
 * @author Romain DUBOIS
 */
public class TransportRsa extends RemoteServiceAdminImpl {

    /** The transport ID */
    private final String mTransportId;
    /** The generic proxy factory */
    private final GenericRemoteServiceFactory mProxyFactory;

    /**
     * Constructor.
     * 
     * @param pId
     *            The related transport ID
     * @param pProxyFactory
     *            The proxy factory
     */
    public TransportRsa(final String pId, final GenericRemoteServiceFactory pProxyFactory) {
        super();

        mTransportId = pId;
        mProxyFactory = pProxyFactory;
    }

    /**
     * Start the service.
     * 
     * @param pReference
     *            The service reference
     */
    @Override
    public void start(final ServiceReference<RemoteServiceAdmin> pReference) {
        super.start(pReference);

        getImplementedIntents().add(nemos.remote.RemoteConstants.INTERCEPTION_INTENT);
    }

    /**
     * {@inheritDoc}
     * 
     * @see nemos.remote.rsa.RemoteServiceAdminImpl#importEndpoint(org.osgi.service.remoteserviceadmin.EndpointDescription,
     *      java.lang.String)
     */
    @Override
    protected ServiceRegistration<?> importEndpoint(final EndpointDescription pEndpoint,
            final String pType) {

        // Check transport is the same as the used one
        final Object lTransport = pEndpoint.getProperties().get(TRANSPORT_ID_PROPERTY);
        if (!CONFIG_NAME.equals(pType) || !mTransportId.equals(lTransport)) {
            return null;
        }

        mProxyFactory.addEndpoint(pEndpoint);

        // Prepare data
        final BundleContext lContext = getBundle().getBundleContext();
        final String[] lClasses = pEndpoint.getInterfaces().toArray(new String[0]);
        final Dictionary<String, ?> lProps = new Hashtable<String, Object>(
                pEndpoint.getProperties());

        // Register proxy
        return lContext.registerService(lClasses, mProxyFactory, lProps);
    }

    /**
     * {@inheritDoc}
     * 
     * @see nemos.remote.rsa.RemoteServiceAdminImpl#export(org.osgi.framework.ServiceReference,
     *      java.util.Map)
     */
    @Override
    protected EndpointDescription export(final ServiceReference<?> pReference,
            final Map<String, Object> pProperties) {

        // Build endpoint ID
        final StringBuilder lEndpointId = new StringBuilder(mTransportId);
        lEndpointId.append(':').append(RemoteUtil.getFrameworkUuid());
        lEndpointId.append(':').append(pReference.getProperty(Constants.SERVICE_ID));
        pProperties.put(RemoteConstants.ENDPOINT_ID, lEndpointId.toString());

        pProperties.put(TRANSPORT_ID_PROPERTY, mTransportId);

        return new EndpointDescription(pReference, pProperties);
    }

    /**
     * {@inheritDoc}
     * 
     * @see nemos.remote.rsa.RemoteServiceAdminImpl#getConfigurations()
     */
    @Override
    protected List<String> getConfigurations() {
        return Collections.singletonList(MessageConfigurationConstants.CONFIG_NAME);
    }
}
